from typing import Optional
import uuid

from fastapi import APIRouter
from pydantic import BaseModel

from DataModels.database import Asset
from DataModels.share import (
    AssetStatus,
    RespInfo,
    RespResultCode,
    StatusInfo,
)
from config import logger
from utils.share import timestamp
from utils.asset import asset_to_info

add_router = APIRouter(prefix="/add")


class AddRequest(BaseModel):
    name: str
    remark: Optional[str] = None
    md5: Optional[str] = None
    size: Optional[int] = None
    format: Optional[str] = None
    small: Optional[str] = None
    snapshot: Optional[str] = None
    url: Optional[str] = None
    owner: Optional[str] = None
    width: Optional[int] = None
    height: Optional[int] = None


@add_router.post("")
async def add_asset(data: AddRequest) -> RespInfo:
    # async def add_asset(data: AddRequest, token=Header(None)) -> RespInfo:
    """
    此端点中， `name` 为必填项。其他为可选。


    |字段| 说明|
    | --- | --- |
    |name| str|
    |remark| Optional[str] = None|
    |md5| Optional[str] = None|
    |size| Optional[int] = None|
    |format| Optional[str] = None|
    |small| Optional[str] = None|
    |snapshot| Optional[str] = None|
    |url| Optional[str] = None|
    |owner| Optional[str] = None|
    |width| Optional[int] = None|
    |height| Optional[int] = None|

    """
    # if (token is None) or (token == ""):
    #     owner = "anonymous"
    # else:
    #     ok, info = check_token(token, check_none=False)
    #     if not ok:
    #         return info  # type: ignore
    #     token = info
    #     phone = token.phone  # type: ignore
    #     user = await User.find_one(User.phone == phone)
    #     if not user:
    #         return RespInfo(
    #             status=StatusInfo(
    #                 code=RespResultCode.PhoneNotFound,
    #                 msg="用户不存在",
    #             )
    #         )
    #     owner = user.uid
    asset = Asset(
        id=str(uuid.uuid4()),
        name=data.name,
        remark=data.remark,
        md5=data.md5,
        format=data.format,
        size=data.size,
        url=data.url,
        small=data.small,
        snapshot=data.snapshot,
        owner=(data.owner or "anonymous"),
        created=timestamp(),
        width=data.width,
        height=data.height,
        status=AssetStatus.Defaule,
    )
    try:
        await asset.insert()  # type: ignore
    except Exception as e:
        logger.error(e)
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.AssetAddFail,
                msg="添加失败AssetInfo失败",
            )
        )
    return RespInfo(
        status=StatusInfo(
            code=RespResultCode.Success,
            msg="添加成功",
        ),
        info=asset_to_info(asset),
    )
